% CALCULATE EYE AND TARGET VELOCITIES
function [v] = velocity(A,sm,scnw,scnwcm,view_dist)

% CALCULATE SCREEN PARAMETERS

Ppcm = scnw/scnwcm;  % Pixels per cm

degpersec = atand((1000/Ppcm)/view_dist);  % = equiv of 1 pixel/ms
                                           % = 1000 pixels/s

% FILTER THE EYE DATA (1st remove NaN from traces)

for i = 1:size(A,1)
    if isnan(A(i,1)) == 0
        B(i,1) = A(i,1);
    end
end

oldSignal = B;

sampling_rate = 1000;
nyquest_freq = sampling_rate/2;
transition_band = [20 30];
attenuation = 30; %80;

[n,Wn] = buttord(transition_band(1)/nyquest_freq,... 
    transition_band(2)/nyquest_freq,3,attenuation);

[b,a]  = butter(n,Wn);

newSignal =  filtfilt(b,a,oldSignal);

% GET GRADIENT AND SMOOTH, CHANGE TO DEG/SEC, TOP UP WITH NaN

vel = gradient(newSignal);

smvel = smooth(vel,sm);   % velocity in pixels/ms

dpsvel = smvel.*degpersec;

try
dpsvel((size(dpsvel,1)+1):msPerCycle,1) = NaN;
end

v = dpsvel;